#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 时间复杂度为 O(n log n)，优于冒泡排序的 O(n²) 空间复杂度是O(n)，弱于冒泡排序的O(1)
def merge_sort(arr):
    """归并排序（递归实现）"""
    if len(arr) <= 1:
        return arr
    
    # 分割数组
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])  # 递归排序左半部分
    right = merge_sort(arr[mid:]) # 递归排序右半部分
    
    # 合并两个有序数组
    return merge(left, right)

def merge(left, right):
    """合并两个有序数组"""
    result = []
    i = j = 0
    
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    
    # 将剩余元素添加到结果中
    result.extend(left[i:])
    result.extend(right[j:])
    return result

# 测试代码
if __name__ == "__main__":
    data = [64, 34, 25, 12, 22, 11, 90, 54, 7, 3]
    print("排序前:", data)
    sorted_data = merge_sort(data)
    print("排序后:", sorted_data)
